/*****  Component, by Ben Bi <prince.bi@gmail.com>  created at: 12/23/2009 4:10:45 PM  *****/

/********   Notes:  *******
 *  Two tags need to be replaced with the module name, they are:
 *  cleanUpFormItem
 *  CleanUpFormItem
 *  clean_up_form
 *  cleanUpForm
 */


/***** variables declartion section, begin *****/
var cleanUpFormItemInputMode = wacFormInputMode.add;
var cleanUpFormItemObj = {};
var cleanUpFormObj = {};

var cleanUpFormItemDataStore = {items:[]};  // to store the items
var cleanUpFormItem_goodsListCurrentPage = 1;
var cleanUpFormItem_goodsListTotalPages = 1;

/***** variables declartion section, end *****/

/***** init section, begin *****/
$(document).ready(
    function() {
        initCleanUpFormItemFormDialog();

        initCleanUpFormItemForm();

        bindCleanUpFormItemEvents();
    }
);

function bindCleanUpFormItemEvents()
{
    $("#cleanUpFormItemFormDialog").bind('dialogopen', function(event, ui)
    {
        initCleanUpFormItemFormData();
//        wacDebugLog("calling " + moduleName + ":" + wacModelObj.cleanUpFormItem.name);//
    });

    $("#cleanUpFormItemFormDialog").bind('dialogclose', function(event, ui)
    {
        $.validationEngine.closePrompt(".formError", true);
    });

    $("#cleanUpFormItem_btnSubmit").bind('click', function (e)
    {
        submitCleanUpFormItemForm();
    });

    $("#cleanUpFormItem_btnClose").bind('click', function (e)
    {
        $("#cleanUpFormItemFormDialog").dialog('close');
    });

    $("#cleanUpFormItem_goods_number, #cleanUpFormItem_goods_number_unit_price").bind('change', function (e)
    {
        $("#cleanUpFormItem_processing_fee").attr("value", Number($("#cleanUpFormItem_goods_number").val()) * Number($("#cleanUpFormItem_goods_number_unit_price").val()));
        $("#cleanUpFormItem_processing_fee").formatCurrency({symbol:"",digitGroupSymbol:"", roundToDecimalPlace:-1});
    });

    $("#cleanUpFormItem_btnPrevStockGoodsList").bind('click', function (e)
    {
        if(cleanUpFormItem_goodsListCurrentPage>1)
        {
            cleanUpFormItem_goodsListCurrentPage--;
            if($('#cleanUpFormItem_clean_up_form_id').val()!="")
            {
                cleanUpFormItemRefleshStockGoodsList(cleanUpFormObj.supplier_id);
            }
        }
    });

    $("#cleanUpFormItem_btnNextStockGoodsList").bind('click', function (e)
    {
        if(cleanUpFormItem_goodsListCurrentPage < cleanUpFormItem_goodsListTotalPages)
        {
            cleanUpFormItem_goodsListCurrentPage++;
            if($('#cleanUpFormItem_clean_up_form_id').val()!="")
            {
                cleanUpFormItemRefleshStockGoodsList(cleanUpFormObj.supplier_id);
            }
        }
    });

    $("#cleanUpFormItem_btnTransferGoods").bind('click', function (e)
    {
        cleanUpFormItemTransferConsumeGoods("#cleanUpFormItem_stockGoodsList", "#cleanUpFormItem_targetGoodsList", "goods_consume_items");
    });

    // fix dialog div didnt remove bug, remove it by this way
    $('#appStorehouseRightPane').bind('tabsremove', function(event, ui) {
        if(ui.panel.id == "t15003")
        {
            $("div[aria-labelledby='ui-dialog-title-cleanUpFormItemFormDialog']").remove();
            $("#cleanUpFormItemFormDialog").remove();
        }
    });
}


function initCleanUpFormItemFormDialog()
{
//    wacDebugLog("initCleanUpFormItemFormDialog.");
    $("#cleanUpFormItemFormDialog").dialog({
            bgiframe: true,
            modal: true,
            width: 950,
            height: 650,
            autoOpen: false,
            buttons: {},
            zIndex: 100
        });
}

function initCleanUpFormItemForm()
{
    $("#cleanUpFormItemGoodsConsumeTabs").tabs();

    $("#cleanUpFormItemForm").validationEngine();

    $('.wacFormContent .left, .wacFormContent input, .wacFormContent textarea, .wacFormContent select').focus(function(){
        $(this).parents('.wacFormContent').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormContent').removeClass("wacFormOver");
    });

    $('.wacFormContentA .left, .wacFormContentA input, .wacFormContentA textarea, .wacFormContentA select').focus(function(){
        $(this).parents('.wacFormRow').addClass("wacFormOver");
    }).blur(function(){
        $(this).parents('.wacFormRow').removeClass("wacFormOver");
    });

    $("#cleanUpFormItem_stockGoodsList").selectable();

    // init the good list css and selectable
    $('ol#cleanUpFormItem_stockGoodsList li').hover(
        function() {
            $(this).addClass('ui-state-hover');
        },
        function() {
            $(this).removeClass('ui-state-hover');
        }
    );

}

function initCleanUpFormItemFormData()
{
    wacShowBlockUILoading("#cleanUpFormItemFormDialog");
    $('#cleanUpFormItem_color_id, #cleanUpFormItem_goods_id, #cleanUpFormItem_goods_number_unit_code').empty();

    var params = {
        "data_format" : 'json',
        "clean_up_form_id": cleanUpFormObj.id
    };

    if(cleanUpFormItemInputMode == wacFormInputMode.add)
    {
        params.id = 0;
    }
    else
    {
        params.id = cleanUpFormItemObj.id;
    }

    $.ajax({
        url: BASE_URL + "cleanUpFormItem/getFormData",
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            initCleanUpFormItemFormDataCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function initCleanUpFormItemFormDataCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       alert(jsonData.info.error_info);
   }
   else
    {
        var selectedIndex = 0;

        for(i=0;i<jsonData['items']['unit'].length;i++)
        {
            $('<option value="' + jsonData['items']['unit'][i].key +'">' + jsonData['items']['unit'][i].value +'</option>').appendTo("#cleanUpFormItem_goods_number_unit_code");
        }

        var itemStr = "";
        cleanUpFormItemEmptyStockGoodsList();
        if(jsonData['items']['stock_goods_items']['items']!=undefined){
            cleanUpFormItem_goodsListTotalPages = jsonData['items']['stock_goods_items']['totalPages'];
            if(cleanUpFormItem_goodsListTotalPages > 1){
                $("#cleanUpFormItem_stockGoodsListPageBtns").show();
            }
            for(i=0;i<jsonData['items']['stock_goods_items']['items'].length;i++)
            {
                itemStr = cleanUpFormItemSetupStockGoodsItemStr(jsonData['items']['stock_goods_items']['items'][i]);
                $(itemStr).appendTo("#cleanUpFormItem_stockGoodsList");
            }
        }

        cleanUpFormItemEmptyTargetGoodsList();
        if(jsonData['items']['target_goods_items']['items']!=undefined){
            for(i=0;i<jsonData['items']['target_goods_items']['items'].length;i++)
            {
                $(cleanUpFormItemDataStore).data(jsonData['items']['target_goods_items']['items'][i].goods_id, jsonData['items']['target_goods_items']['items'][i].goods_id);

                itemStr = cleanUpFormItemSetupTargetGoodsItemStr(jsonData['items']['target_goods_items']['items'][i], "goods_consume_items", false);
                $(itemStr).appendTo("#cleanUpFormItem_targetGoodsList");
            }
        }
   }

   setupCleanUpFormItemFormDefaultValues(jsonData['items']['default']);

   wacHideBlockUI("#cleanUpFormItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}

function setupCleanUpFormItemFormDefaultValues(defaultValueObj)
{
    $("#cleanUpFormItem_clean_up_form_id").attr("value", cleanUpFormObj.id);
    $("#cleanUpFormItem_clean_up_form_code").attr("innerHTML", cleanUpFormObj.code);
    $("#cleanUpFormItem_production_order_code").attr("innerHTML", cleanUpFormObj.production_order_code);
    $("#cleanUpFormItem_supplier_name").attr("innerHTML", cleanUpFormObj.supplier_name);

    if(cleanUpFormItemInputMode == wacFormInputMode.add)   // use default values
    {
        $("#cleanUpFormItem_id").attr("value", 0);
        $('#cleanUpFormItem_goods_id').flexbox(BASE_URL + 'goods/GetCleanUpHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_id",
            inputName: "goods_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $('#cleanUpFormItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            //            resultTemplate: '<div class="col1">{id}</div><div class="col2">{name}</div>',
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            inputName: "color_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });

        $("#cleanUpFormItem_goods_number_unit_code option:[value='"+ cleanUpFormObj.goods_amount_unit_code +"']").attr('selected', 'selected');
    }
    else  // use edit obj values
    {
        $('#cleanUpFormItem_goods_id').flexbox(BASE_URL + 'goods/GetCleanUpHashInFormat?data_format=jsonFlexbox', {
            initialValue: cleanUpFormItemObj.goods_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "goods_id",
            inputName: "goods_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpFormItem_goods_id_input').val(cleanUpFormItemObj.goods_name);

        $('#cleanUpFormItem_color_id').flexbox(BASE_URL + 'color/GetIdNameHashInFormat?data_format=jsonFlexbox', {
            initialValue: cleanUpFormItemObj.color_id,
            watermark: '请输入选择...',
            noResultsText : '没找到相符项!',
            width: 200,
            maxVisibleRows: 15,
            autoCompleteFirstMatch: true,
            queryDelay: 200,
            minChars: 1,
            paramName: "color_id",
            inputName: "color_name",
            onSelect: function() {
//                wacDebugLog('You selected "' + this.value + '", ' +
//                    'which has a hidden value of ' + this.getAttribute('hiddenValue'));
            }
        });
        $('#cleanUpFormItem_color_id_input').val(cleanUpFormItemObj.color_name);

//        $("#cleanUpFormItem_batch").attr("value", cleanUpFormItemObj.batch);
        $("#cleanUpFormItem_processing_fee").attr("value", cleanUpFormItemObj.processing_fee);
        $("#cleanUpFormItem_goods_number_unit_price").attr("value", cleanUpFormItemObj.goods_number_unit_price);
        $("#cleanUpFormItem_goods_number").attr("value", cleanUpFormItemObj.goods_number);
        $("#cleanUpFormItem_id").attr("value", cleanUpFormItemObj.id);

        $("#cleanUpFormItem_memo").attr("value", cleanUpFormItemObj.memo);

        $("#cleanUpFormItem_goods_number_unit_code option:[value='"+ cleanUpFormItemObj.goods_number_unit_code +"']").attr('selected', 'selected');
    }

//wacDebugLog($.dump(cleanUpFormItemObj));
//    wacDebugLog($.dump(cleanUpFormObj));
//    wacDebugLog($.dump(defaultValueObj));
//    wacDebugLog("cleanUpFormItemInputMode: " + cleanUpFormItemInputMode);

}
/***** init section, end *****/


/**************  interaction section, begin  ***************/

function cleanUpFormItemOpenModuleForm(moduleFormName, moduleName, inputMode, rowid, parentId)
{
    cleanUpFormItemInputMode = inputMode;

    $(cleanUpFormItemDataStore).removeData();  // empty data store

    if(parentId === undefined || parentId==0){
        cleanUpFormObj = {};
    }
    else
    {
        cleanUpFormObj = $("#cleanUpFormList").getRowData(parentId);
    }

    if(rowid === undefined || rowid==0){
        cleanUpFormItemObj = {};
    }
    else
    {
        cleanUpFormItemObj = $("#cleanUpFormList_" + cleanUpFormObj.id + "_t").getRowData(rowid);
    }

    $('#'+moduleFormName).dialog('open');
}

function validateCleanUpFormItemForm()
{
    var validateFlag = true;

    if (!$("#cleanUpFormItemForm").validationEngine({returnIsValid:true}))
    {
        validateFlag = false;
        return validateFlag;
    }

    if(validateFlag && $("#cleanUpFormItem_targetGoodsList li").length == 0)
    {
        wacShowTips("请输入消耗的纺织布项目!");
        validateFlag = false;
    }

    return validateFlag;
}

function submitCleanUpFormItemForm()
{
    if(!validateCleanUpFormItemForm()){
        return;
    }

    wacShowBlockUILoading("#cleanUpFormItemFormDialog", "处理中...");

    var extraParams = "data_format=json";
    var submitUrl;

    if(cleanUpFormItemInputMode == wacFormInputMode.add){
        submitUrl = BASE_URL + "cleanUpFormItem/add";
    }
    else{
        submitUrl = BASE_URL + "cleanUpFormItem/edit";
    }


    $.ajax({
        url: submitUrl,
//        url: BASE_URL + "test/ajaxTest" ,
        global: true,
        type: "GET",
        data: $("#cleanUpFormItemForm").serialize() + "&" + extraParams,
        dataType: "json",
        success: function(jsonData){
            submitCleanUpFormItemFormCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function submitCleanUpFormItemFormCallBack(jsonData)
{
   if(jsonData.info.status == wacOperationStatus.Error)
   {
       wacShowTips(jsonData.info.error_info);
   }
   else
   {
       wacShowTips(jsonData.info.tips);
       $("#cleanUpFormList_" + cleanUpFormObj.id + "_t").trigger("reloadGrid");
   }

   wacHideBlockUI("#cleanUpFormItemFormDialog");

//   wacDebugLog($.dump(jsonData));
}





function cleanUpFormItemTransferConsumeGoods(srcGoodsListId, targetGoodsListId, varName)
{
   $(".ui-selected", $(srcGoodsListId)).each(function(){
       if($(cleanUpFormItemDataStore).data($(this).attr("goods_id")) === undefined)
       {
           $(cleanUpFormItemDataStore).data($(this).attr("goods_id"), $(this).attr("goods_id"));
//           wacDebugLog($(this).attr("goods_id") + ": " + $(this).attr("goods_number") + ": " + $(this).html());
            var itemStr = cleanUpFormItemSetupTargetGoodsItemStr(this, varName, true);
            $(itemStr).appendTo(targetGoodsListId);
       }
   });
}


function cleanUpFormItemSetupTargetGoodsItemStr(objItem, varName, isStock)
{
   if(isStock){   // obj come from stock
       var tmpStr = '<li class="ui-widget-content wacCursor">' + $(objItem).attr("goods_name") ;
           tmpStr += '>&nbsp;消耗量:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][consume_amount]" value="' + $(objItem).attr("goods_number") + '" maxNumber="' + $(objItem).attr("goods_number") + '" class="validate[required,custom[onlyNumber]] wacFormText" style="width: 45px;">';
//           tmpStr += '&nbsp;每码用量:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][unit_consume]" value="0" class="validate[required,custom[onlyNumber]] wacFormText" style="width: 30px;">';
//           tmpStr += '&nbsp;每码应用量:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][expect_consume]" value="0" class="validate[required,custom[onlyNumber]] wacFormText" style="width: 30px;">';
           tmpStr += '&nbsp;损耗率:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][attrition_rate]" value="0" class="validate[required,custom[onlyDigit]] wacFormText" style="width: 30px;">%';
           tmpStr += '<span class="ui-icon ui-icon-circle-minus" style="float:right" onclick="javascript: cleanUpFormItemRemoveItem(this, '+ $(objItem).attr("goods_id") +');"></span>';
           tmpStr += '</li>';
   }
   else{  // come from consume
       var tmpStr = '<li class="ui-widget-content wacCursor">' + $(objItem).attr("goods_name") ;
           tmpStr += '>&nbsp;消耗量:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][consume_amount]" value="' + $(objItem).attr("unit_consume_amount") + '" maxNumber="' + $(objItem).attr("unit_consume_amount") + '" class="validate[required,custom[onlyNumber]] wacFormText" style="width: 45px;">';
//           tmpStr += '&nbsp;每码用量:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][unit_consume]" value="' + $(objItem).attr("unit_unit_consume") + '" class="validate[required,custom[onlyNumber]] wacFormText" style="width: 30px;">';
//           tmpStr += '&nbsp;每码应用量:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][expect_consume]" value="' + $(objItem).attr("unit_expect_consume") + '" class="validate[required,custom[onlyNumber]] wacFormText" style="width: 30px;">';
           tmpStr += '&nbsp;损耗率:&nbsp;<input type="text" id="cleanUpFormItem_id_' + $(objItem).attr("goods_id") +'" name="'+ varName +'[id_' + $(objItem).attr("goods_id") + '][attrition_rate]" value="' + $(objItem).attr("attrition_rate") + '" class="validate[required,custom[onlyDigit]] wacFormText" style="width: 40px;">%';
           tmpStr += '<span class="ui-icon ui-icon-circle-minus" style="float:right" onclick="javascript: cleanUpFormItemRemoveItem(this, '+ $(objItem).attr("goods_id") +');"></span>';
           tmpStr += '</li>';
   }
    return tmpStr;
}

function cleanUpFormItemRemoveItem(tagObj, goodId)
{
    $(tagObj).parent().remove();
    $(cleanUpFormItemDataStore).removeData(goodId);
}

function cleanUpFormItemSetupStockGoodsItemStr(objItem)
{
    var tmpStr = '<li class="ui-widget-content wacCursor" goods_id="' + $(objItem).attr("goods_id") +'" goods_number="' + $(objItem).attr("goods_number")+' "';
        tmpStr += 'goods_name="' + $(objItem).attr("goods_name") + ' " goods_number_unit_code_name="' + $(objItem).attr("goods_number_unit_code_name") +'" >';
        tmpStr += $(objItem).attr("goods_name") + "&nbsp;" + $(objItem).attr("goods_number") + "&nbsp;" + $(objItem).attr("goods_number_unit_code_name") +'</li>';
    return tmpStr;
}

function cleanUpFormItemEmptyStockGoodsList()
{
    $("#cleanUpFormItem_stockGoodsZone li").remove();
    $("#cleanUpFormItem_stockGoodsListPageBtns").hide();
}

function cleanUpFormItemEmptyTargetGoodsList()
{
    $("#cleanUpFormItem_targetGoodsZone li").remove();
}

function cleanUpFormItemRefleshStockGoodsList(id)
{
    wacShowBlockUILoading("#cleanUpFormItem_stockGoodsZone", "装载中...");

    var submitUrl;
    var params = {
        "data_format" : 'json',
        "factory_id" : id,
        "rows" :5,
        "page" : cleanUpFormItem_goodsListCurrentPage
    };

    submitUrl = BASE_URL + "factory/GetStockGoodsList";
//    submitUrl = BASE_URL + "test/ajaxTest";
    $.ajax({
        url: submitUrl,
        global: true,
        type: "GET",
        data: params,
        dataType: "json",
        success: function(jsonData){
            cleanUpFormItemRefleshStockGoodsListCallBack(jsonData);
        },
        error: function(XMLHttpRequest, textStatus, errorThrown){
            wacDebugLog("getFormData Error: " + $(this).dump()); // the options for this ajax request
        }
    });
}

function cleanUpFormItemRefleshStockGoodsListCallBack(jsonData)
{
    if(jsonData.info.status == wacOperationStatus.Error)
    {
        wacShowTips(jsonData.info.error_info);
    }
    else
    {
        cleanUpFormItemEmptyStockGoodsList();
        cleanUpFormItem_goodsListTotalPages = jsonData.totalPages;
        if(cleanUpFormItem_goodsListTotalPages > 1){
            $("#cleanUpFormItem_stockGoodsListPageBtns").show();
        }
        for(i=0;i<jsonData['items'].length;i++)
        {
            var itemStr = cleanUpFormItemSetupStockGoodsItemStr(jsonData['items'][i]);
            $(itemStr).appendTo("#cleanUpFormItem_stockGoodsList");
        }
//        wacShowTips(jsonData.info.tips);
    }

    wacHideBlockUI("#cleanUpFormItem_stockGoodsZone");
}


/**************  interaction section, end  ***************/